package boot

import (
	"gino/global"
	"gino/pkg/glog"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/clients/config_client"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"gopkg.in/yaml.v2"
	"log"
)

// 配置
var (
	namespaceId = "170ddc09-ca25-436f-b04c-000e309d6109"
	ipAddr      = "39.97.105.9"
	port        = 9099
	dataId      = "861"
	group       = "Gin"
)

func Nacos() {

	// create clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         namespaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,        // http请求超时时间，单位毫秒
		NotLoadCacheAtStart: true,
		LogDir:              "tmp/nacos/log",

		CacheDir: "tmp/nacos/cache",
		//RotateTime:   "1h",
		//MaxAge:       3,
		LogLevel:     "debug",
		BeatInterval: 5 * 1000, // 心跳间隔时间，单位毫秒（仅在ServiceClient中有效）
	}

	// create serverConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      ipAddr,
			ContextPath: "/nacos",
			Port:        uint64(port),
			Scheme:      "http",
		},
	}

	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	if err != nil {
		log.Fatal(err.Error())
	}

	// 获取配置
	data, err := configClient.GetConfig(vo.ConfigParam{
		DataId: dataId,
		Group:  group,
	})

	// 解析赋值配置文件
	if err := yaml.Unmarshal([]byte(data), &global.Config); err != nil {
		log.Fatal("Failed to unmarshal yaml configuration file")
	}

	// 监听nacos配置
	go ListenConfig(configClient)

	return
}

// ListenConfig 监听nacos配置
func ListenConfig(configClient config_client.IConfigClient) {
	err := configClient.ListenConfig(vo.ConfigParam{
		DataId: dataId,
		Group:  group,
		OnChange: func(namespace, group, dataId, data string) {
			// 解析赋值配置文件
			if err := yaml.Unmarshal([]byte(data), &global.Config); err != nil {
				panic("Failed to unmarshal yaml configuration file")
			}

			// 重新加载服务
			glog.NewZapLogger()
			Mysql()
			Redis()
		},
	})
	if err != nil {
		log.Fatal("Nacos Listen config failed " + err.Error())
	}

}
